//
//  PersonalInfoViewController.m
//  YunGou
//
//  Created by macbook on 16/5/18.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "ModifyPersonalInfoViewController.h"
#import "GengerViewController.h"
#import "YGPickView.h"
#import <UIButton+WebCache.h>

#define User(attribute) [UserModel sharedInstance].attribute

@interface PersonalInfoViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (nonatomic,strong) NSArray *leftArray;
@property (nonatomic,strong) NSArray *rightArray;
@property (nonatomic,strong) UIButton *headImageBtn;
@property (nonatomic,strong) YGPickView *pickView;
@property (nonatomic,strong) UIDatePicker *datePick;
@property (nonatomic,strong) UIPickerView *areaPicker;
@property (nonatomic,copy) NSString *pickType;

@property (nonatomic,strong) NSArray *provinceArr;
@property (nonatomic,strong) NSArray *cityArr;
@property (nonatomic,strong) NSArray *districtArr;
@property (nonatomic,assign) NSInteger provinceIndex;
@property (nonatomic,assign) NSInteger cityIndex;
@property (nonatomic,assign) NSInteger districtIndex;
@property (nonatomic,copy) NSString *allName;
@end

@implementation PersonalInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _leftArray = @[@"昵称",@"性别",@"生日",@"QQ",@"邮箱",@"现居地"];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _rightArray = @[User(img),User(username),User(gender),User(birth),User(qq),User(email),User(address)];
    if (_isReload) {
        [self.tableView reloadData];
    }
}

#pragma tableViewDelegte and DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    if (indexPath.row == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        _headImageBtn = [cell.contentView viewWithTag:1];
        _headImageBtn.layer.cornerRadius = _headImageBtn.frame.size.width / 2;
        _headImageBtn.clipsToBounds = YES;
        if ([_rightArray[0] isEqualToString:@""]) {
            [_headImageBtn setBackgroundImage:[UIImage imageNamed:@"sdfx_toux"] forState:UIControlStateNormal];
        }else{
            [_headImageBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:[ImageUrl stringByAppendingString:_rightArray[indexPath.row]]] forState:UIControlStateNormal];
        }
        [_headImageBtn addTarget:self action:@selector(modifyHeadImage) forControlEvents:UIControlEventTouchUpInside];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        UILabel *leftLabel = [cell.contentView viewWithTag:1];
        leftLabel.text = _leftArray[indexPath.row - 1];
        UILabel *rightLabel = [cell.contentView viewWithTag:2];
        rightLabel.text = _rightArray[indexPath.row];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 93;
    }return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ((indexPath.row > 3 && indexPath.row != 6)||indexPath.row == 1) {
        ModifyPersonalInfoViewController *modifyVC = SB(@"Setting", @"ModifyVC");
        if (indexPath.row == 1) {
            modifyVC.type = UserName;
            modifyVC.title = @"修改昵称";
        }else if (indexPath.row == 4){
            modifyVC.type = QQ;
            modifyVC.title = @"修改QQ";
        }else if (indexPath.row == 5){
            modifyVC.type = Email;
            modifyVC.title = @"修改邮箱";
        }
        
        [self.navigationController pushViewController:modifyVC animated:YES];
    }else{
        if (indexPath.row == 2) {
            GengerViewController *genderVC = SB(@"Setting", @"GenderVC");
            [self.navigationController pushViewController:genderVC animated:YES];
        }else if (indexPath.row == 3) {
            if (_areaPicker) {
                [_areaPicker removeFromSuperview];
                _areaPicker = nil;
            }
            self.datePick.frame = CGRectMake(0, 0, ScreenWidth - 12, self.pickView.bottomView.bounds.size.height);
            
            [self.pickView.bottomView addSubview:self.datePick];
            _pickType = @"date";
        }else if(indexPath.row == 6){
            if (_datePick) {
                [_datePick removeFromSuperview];
                _datePick = nil;
            }
            [self loadArea];
            self.areaPicker.frame = CGRectMake(0, 0, ScreenWidth - 12, self.pickView.bottomView.bounds.size.height);
            [self.pickView.bottomView addSubview:self.areaPicker];
            _pickType = @"area";
        }
    }
}

//加载地址
- (void)loadArea{
    NSString *provincePath = [[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
    NSData *provinceData = [NSData dataWithContentsOfFile:provincePath];
    NSDictionary *provinceDic = [NSJSONSerialization JSONObjectWithData:provinceData options:kNilOptions error:nil];
    _provinceArr = [provinceDic objectForKey:@"province"];
    
    id cityItem = [_provinceArr objectAtIndex:0];
    NSString *cityFilePath = [[NSBundle mainBundle] pathForResource:[cityItem objectForKey:@"spellName"] ofType:@"json"];
    NSData *cityData = [NSData dataWithContentsOfFile:cityFilePath];
    NSDictionary *cityDic = [NSJSONSerialization JSONObjectWithData:cityData options:kNilOptions error:nil];
    _cityArr = [cityDic objectForKey:@"city"];
    
    id districtItem = [_cityArr objectAtIndex:0];
    NSString *districtFilePath = [[NSBundle mainBundle] pathForResource:[districtItem objectForKey:@"spellName"] ofType:@"json"];
    NSData *districtData = [NSData dataWithContentsOfFile:districtFilePath];
    NSDictionary *districtDic = [NSJSONSerialization JSONObjectWithData:districtData options:kNilOptions error:nil];
    _districtArr = [districtDic objectForKey:@"district"];
    _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:0] objectForKey:@"name"], [[_cityArr objectAtIndex:0] objectForKey:@"name"], [[_districtArr objectAtIndex:0] objectForKey:@"name"]];
}

#pragma -mark 更换用户头像
- (void)modifyHeadImage{
    UIAlertController *alerVc = [UIAlertController alertControllerWithTitle:@"选择您的照片" message:@"您可以从相机拍摄照片或者从相册中选择" preferredStyle:UIAlertControllerStyleActionSheet];
    __weak __typeof(self)weakSelf = self;
    UIAlertAction *actionCamera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf pickImageBySourceType:UIImagePickerControllerSourceTypeCamera];
    }];
    
    UIAlertAction *actionImagePicker = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf pickImageBySourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    [alerVc addAction:actionCamera];
    [alerVc addAction:actionImagePicker];
    [alerVc addAction:actionCancel];
    [self presentViewController:alerVc animated:YES completion:nil];
}

- (void)pickImageBySourceType:(UIImagePickerControllerSourceType)sourceType
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate   = (id)self;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    _isReload = NO;
    [self dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = (UIImage *)info[@"UIImagePickerControllerOriginalImage"];
    [_headImageBtn setBackgroundImage:image forState:UIControlStateNormal];
    [NetWorkTool uploadWithImage:image success:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            NSMutableString *path = object[@"path"];
            NSString *subStr = [path substringFromIndex:18];
            [NetWorkTool updateUserInfoWithNickName:nil img:subStr gender:nil birth:nil qq:nil email:nil address:nil success:^(id object) {
                if ([object[@"code"] integerValue] == 1) {
                    [MBProgressHUD showSuccess:@"上传成功"];
                    [[UserModel sharedInstance] setValue:subStr forKey:@"img"];
                }
            } failure:^(NSError *error) {
                
            }];
        }
    } failure:^(NSError *error) {
        FZLog(@"%@",error);
    }];
}

#pragma -mark pickViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSInteger row = 0;
    switch (component)
    {
        case 0:
            row = [_provinceArr count];
            break;
        case 1:
            row = [_cityArr count];
            break;
        case 2:
            row = [_districtArr count];
            break;
        default:
            break;
    }
    return row;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *title = @"";
    id item;
    switch (component)
    {
        case 0:
            item = [_provinceArr objectAtIndex:row];
            _provinceIndex = row;
            break;
        case 1:
            item = [_cityArr objectAtIndex:row];
            _cityIndex = row;
            break;
        case 2:
            item = [_districtArr objectAtIndex:row];
            _districtIndex = row;
            break;
        default:
            break;
    }
    if (item)
    {
        title = [item objectForKey:@"name"];
    }
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (0 == component)
    {
        id cityItem = [_provinceArr objectAtIndex:row];
        NSString *cityFilePath = [[NSBundle mainBundle] pathForResource:[cityItem objectForKey:@"spellName"] ofType:@"json"];
        if (cityFilePath)
        {
            NSData *cityData = [NSData dataWithContentsOfFile:cityFilePath];
            NSDictionary *cityDic = [NSJSONSerialization JSONObjectWithData:cityData options:kNilOptions error:nil];
            _cityArr = [cityDic objectForKey:@"city"];
            
            id districtItem = [_cityArr objectAtIndex:0];
            NSString *districtFilePath = [[NSBundle mainBundle] pathForResource:[districtItem objectForKey:@"spellName"] ofType:@"json"];
            if (districtFilePath)
            {
                NSData *districtData = [NSData dataWithContentsOfFile:districtFilePath];
                NSDictionary *districtDic = [NSJSONSerialization JSONObjectWithData:districtData options:kNilOptions error:nil];
                _districtArr = [districtDic objectForKey:@"district"];
            } else {
                _districtArr = [[NSArray alloc] init];
            }
        } else {
            _cityArr = [[NSArray alloc] init];
            _districtArr = [[NSArray alloc] init];
        }
        
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:1 animated:NO];
        [pickerView selectRow:0 inComponent:2 animated:NO];
        
        _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:row] objectForKey:@"name"], [[_cityArr objectAtIndex:0] objectForKey:@"name"], [[_districtArr objectAtIndex:0] objectForKey:@"name"]];
    }
    
    if (1 == component)
    {
        id districtItem = [_cityArr objectAtIndex:row];
        NSString *districtFilePath = [[NSBundle mainBundle] pathForResource:[districtItem objectForKey:@"spellName"] ofType:@"json"];
        if (districtFilePath)
        {
            NSData *districtData = [NSData dataWithContentsOfFile:districtFilePath];
            NSDictionary *districtDic = [NSJSONSerialization JSONObjectWithData:districtData options:kNilOptions error:nil];
            _districtArr = [districtDic objectForKey:@"district"];
        } else {
            _districtArr = [[NSArray alloc] init];
        }
        
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:2 animated:NO];
        
        _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:_provinceIndex] objectForKey:@"name"], [[_cityArr objectAtIndex:row] objectForKey:@"name"], [[_districtArr objectAtIndex:0] objectForKey:@"name"]];
    }
    
    if (2 == component) {
        _allName = [NSString stringWithFormat:@"%@%@%@", [[_provinceArr objectAtIndex:_provinceIndex] objectForKey:@"name"], [[_cityArr objectAtIndex:_cityIndex] objectForKey:@"name"], [[_districtArr objectAtIndex:row] objectForKey:@"name"]];
    }
}

#pragma -mark 懒加载相关
- (YGPickView *)pickView{
    if (!_pickView) {
        _pickView = [YGPickView nibInitializtion];
        _pickView.userInteractionEnabled = YES;
        _pickView.frame = CGRectMake(0,ScreenHeight - 305 - 49, ScreenWidth, 305);
        __weak typeof(self) ws = self;
        _pickView.pickerViewBlock = ^(NSInteger tag){
            if ([ws.pickType isEqualToString:@"date"]) {
                if (tag == 2) {
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyy-MM-dd";
                    UITableViewCell *cell = [ws.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
                    UILabel *dateLabel = [cell.contentView viewWithTag:2];
                    NSString *birthday = [formatter stringFromDate:ws.datePick.date];
                    dateLabel.text = birthday;
                    [MBProgressHUD showMessage:@"正在修改"];
                    [NetWorkTool updateUserInfoWithNickName:nil img:nil gender:nil birth:birthday qq:nil email:nil address:nil success:^(id object) {
                        [MBProgressHUD hideHUD];
                        if ([object[@"code"] integerValue] == 1) {
                            [MBProgressHUD showSuccess:@"修改成功"];
                            [[UserModel sharedInstance] setValue:birthday forKey:@"birth"];
                        }
                    } failure:^(NSError *error) {
                        
                    }];
                }
            }else if([ws.pickType isEqualToString:@"area"]){
                if (tag == 2) {

                    UITableViewCell *cell = [ws.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:0]];
                    UILabel *areaLabel = [cell.contentView viewWithTag:2];
                    areaLabel.text = ws.allName;
                    [NetWorkTool updateUserInfoWithNickName:nil img:nil gender:nil birth:nil qq:nil email:nil address:ws.allName success:^(id object) {
                        if ([object[@"code"] integerValue] == 1) {
                            [MBProgressHUD showSuccess:@"地址修改成功"];
                            [[UserModel sharedInstance] setValue:ws.allName forKey:@"address"];
                        }else{
                            [MBProgressHUD showError:@"地址修改失败"];
                        }
                    } failure:^(NSError *error) {
                        
                    }];
                }
            }
            [ws.pickView removeFromSuperview];
            ws.pickView = nil;
            _pickType = nil;
        };
        [self.tableView addSubview:_pickView];
    }
    return _pickView;
}

- (UIDatePicker *)datePick{
    if (!_datePick) {
        _datePick = [[UIDatePicker alloc] init];
        [_datePick setDatePickerMode:UIDatePickerModeDate];
        _datePick.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh"];
        NSDate *maxDate = [NSDate date];
        NSDateFormatter *formatter_maxDate = [[NSDateFormatter alloc] init];
        [formatter_maxDate setDateFormat:@"yyyy"];
        NSInteger minInt = [[formatter_maxDate stringFromDate:maxDate] integerValue] - 70;
        
        NSDateFormatter *formatter_minDate = [[NSDateFormatter alloc] init];
        [formatter_minDate setDateFormat:@"yyyy-MM-dd"];
        
        NSDate *minDate = [formatter_minDate dateFromString:[NSString stringWithFormat:@"%ld-01-01",minInt]];
        [_datePick setMinimumDate:minDate];
        [_datePick setMaximumDate:maxDate];
    }
    return _datePick;
}

- (UIPickerView *)areaPicker{
    if (!_areaPicker) {
        _areaPicker = [[UIPickerView alloc] init];
        _areaPicker.delegate = self;
        _areaPicker.dataSource = self;
    }
    return _areaPicker;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _isReload = YES;
}

@end
